package edu.dublbo.app.habitplusfavorite.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.dublbo.app.habitplusfavorite.mapper.ResourceMapper;
import edu.dublbo.app.habitplusfavorite.model.Resource;
import edu.dublbo.app.habitplusfavorite.service.IResourceService;
import edu.dublbo.app.habitplusfavorite.util.Constants;
import edu.dublbo.app.habitplusfavorite.vo.ResourceVo;
import edu.dublbo.commons.lang.PageResult;
import edu.dublbo.commons.lang.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.List;

/**
 * <p>
 * 资源 服务实现类
 * </p>
 *
 * @author habitplus
 * @since 2021-11-29
 */
@Slf4j
@Service
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> implements IResourceService {
    @Value("${logo-img.local-path}")
    private String logoLocPath;

    @Override
    public PageResult<Resource> listOfPage(int page, int limit) {
        Page<Resource> pageBean = new Page<>(page, limit);
        IPage<Resource> pageData = baseMapper.selectPageVo(pageBean);

        return PageResult.<Resource>builder()
                .code(ResultEnum.SUCCESS.getCode())
                .msg(ResultEnum.SUCCESS.getMsg())
                .data(pageData.getRecords())
                .count(pageData.getTotal())
                .build();
    }

    @Override
    @Transactional
    public void delete(int id) {
        Resource r = baseMapper.selectById(id);
        if (r == null) return;
        String logo = r.getLogo();
        if (!StringUtils.isEmpty(logo)) {
            // 没有设置图片
            if (logo.startsWith(Constants.LOGO_REQUEST_PREFIX)) {
                String filePath = logoLocPath + File.separator
                        + logo.substring(Constants.LOGO_REQUEST_PREFIX.length() - 1);
                File file = new File(filePath);

                if (file.exists() && file.isFile())
                    if (file.delete())
                        log.warn("已删除文件：{}", filePath);

            }
        }
        baseMapper.deleteById(id);
    }

    @Override
    public List<ResourceVo> listOfGroup() {
        // 获取资源列表
        return baseMapper.selectListOfGroup();
    }
}
